/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.jaiz.twitter.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.jaiz.twitter.model.Usuario;

/**
 *
 * @author EmeDe
 */
@WebServlet(name = "UploadPhotoServlet", urlPatterns = {"/uploadphoto"})
public class UploadPhotoServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {        
     
            /*
             * TODO output your page here. You may use following sample code.
             */
            /*out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet UploadPhotoServlet</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println(getServletContext().getRealPath("/"));
            out.println("<h1>Servlet UploadPhotoServlet at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");*/
            processFile(request);
            response.sendRedirect("home");
    
    }
    
     public boolean processFile(HttpServletRequest request) {
        try {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(1024*5000);
            factory.setRepository(new File("res/img"));
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setSizeMax(1280 * 5000);
            List fileItems = upload.parseRequest(request);
            if (fileItems == null) {
                depura("No ha cargado ninguna imagen");
                return false;
            }

            //out.print("<br>El número de ficheros subidos es: " + fileItems.size());

            // Iteramos por cada fichero
            Iterator i = fileItems.iterator();
            FileItem actual = null;
            depura("estamos en la iteración");
            
            if(i.hasNext()){  //Si existe un archivo
                actual = (FileItem) i.next();
                String fileName = actual.getName();
                //out.println("<br>Imagen seleccionada: " + fileName);
                // construimos un objeto file para recuperar el trayecto completo
                File fichero = new File(fileName);
                depura("El nombre del fichero es " + fichero.getName());
                Usuario usuario = (Usuario) request.getSession().getAttribute("user");
                // nos quedamos solo con el nombre y descartamos el path                
                fichero = new File(getServletContext().getRealPath("/") + "res/img/"+usuario.getUserName()+".jpg");
                actual.write(fichero);
            }
        } catch (Exception e) {
            Logger.getLogger(UploadPhotoServlet.class.getName()).log(Level.SEVERE, e.getMessage());
            return false;
        }

        return true;
    }

    void depura(String cadena) {
        System.out.println("El error es " + cadena);
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
